package com.dfire.monitor.service.impl;

import java.util.Optional;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;

import com.dfire.common.config.Alarm;
import com.dfire.common.entity.HeraJob;
import com.dfire.common.entity.HeraSso;
import com.dfire.common.enums.AlarmLevel;
import com.dfire.common.service.HeraJobService;
import com.dfire.common.util.ActionUtil;
import com.dfire.common.vo.JobElement;
import com.dfire.event.HeraJobFailedEvent;
import com.dfire.monitor.config.SmsConfig;
import com.dfire.monitor.domain.CbestAlarmInfo;
import com.dfire.monitor.service.AlarmCenter;

/**
 * 电话告警 使用者自己实现
 *
 * @author xiaosuda
 * @date 2019/3/6
 */
@Alarm
public class PhoneJobFailAlarm extends AbstractJobFailAlarm {

    @Autowired
    private AlarmCenter alarmCenter;
    
    @Autowired
    private SmsConfig smsConfig;
    
    @Autowired
    private HeraJobService heraJobService;

    @Override
    public void alarm(HeraJobFailedEvent failedEvent, Set<HeraSso> monitorUser) {
        HeraJob heraJob = failedEvent.getHeraJob();
        //低于电话等级直接跳过
        if (AlarmLevel.lessThan(heraJob.getOffset(), AlarmLevel.PHONE) || heraJob.getAuto() != 1) {
            return;
        }
        CbestAlarmInfo alarmInfo = new CbestAlarmInfo();
        alarmInfo.setParams(buildJobAlertParams(heraJob, failedEvent.getRunCount(), monitorUser));
        alarmInfo.setTemplateId(smsConfig.getFailId());
        Optional.ofNullable(monitorUser).ifPresent(users -> {
        	alarmInfo.setPhones(users.stream().map(HeraSso::getPhone).toArray(String[]::new));
        	alarmCenter.sendToPhone(alarmInfo);
        }
       );
    }

    @Override
    public void alarm(JobElement element, Set<HeraSso> monitorUser) {

    	 int id = ActionUtil.getJobId(element.getJobId());
         HeraJob heraJob = heraJobService.findById(id);
         
         //低于电话等级直接跳过
         if (AlarmLevel.lessThan(heraJob.getOffset(), AlarmLevel.PHONE) || heraJob.getAuto() != 1) {
             return;
         }
         
          CbestAlarmInfo alarmInfo = new CbestAlarmInfo();
          alarmInfo.setParams(buildTimeoutAlertParams(element, monitorUser));
          alarmInfo.setTemplateId(smsConfig.getTimeoutId());
          
          Optional.ofNullable(monitorUser).ifPresent(users -> {
          	alarmInfo.setPhones(users.stream().map(HeraSso::getPhone).toArray(String[]::new));
          	alarmCenter.sendToPhone(alarmInfo);
          }
         );
    }
}
